import os
import sys

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, BASE_DIR)
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import requests
import json
from tools.log import logger
import settings
import traceback

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
}


def auth_task_state(task_id):
    try:
        rel_path = '/v1/select_task'
        req_url = settings.SELECT_TASK_URL + rel_path
        data = {
            'id': task_id,
            'key': settings.CLIENT_KEY
        }
        resp = requests.post(req_url, json=data, headers=headers)
        # print(resp.status_code, resp.text)
        if resp.status_code != 200:
            print(resp.status_code, resp.text)
            logger.error("任务状态验证失败，任务未找到或者任务已经完成")
            logger.error(resp.text)
            return True
        else:
            ret_data = json.loads(resp.text)
            if ret_data.get('code') != 1:
                print(resp.status_code, resp.text)
                logger.error("任务状态验证失败，任务未找到或者任务已经完成")
                logger.error(resp.text)
                return True
            else:
                data = ret_data.get('data')
                state = data['state']
                if state not in [1, 2]:
                    print(resp.status_code, resp.text)
                    logger.error("任务状态验证失败，任务未找到或者任务已经完成")
                    logger.error(resp.text)
                    return True
            return False
    except:
        logger.error("auth_task_state error")
        logger.error(traceback.format_exc())
        return True


if __name__ == "__main__":
    
    t_id = 12
    ret = auth_task_state(t_id)
    print(ret)